package com.common.tools.controller;

import com.common.convert.ConverterConfig;
import com.common.convert.ConverterRouter;
import com.common.convert.param.ConvertInput;
import com.common.convert.param.ConvertResult;
import com.common.tools.model.Result;
import com.common.tools.utils.MultipartFileUtils;
import org.jodconverter.core.DocumentConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

@RestController
@RequestMapping("convert/")
public class ConvertController {

    @Autowired
    private DocumentConverter documentConverter;
    private ConverterRouter converterRouter;

    @Value("${converter.workDir}")
    private String workDir;

    public ConvertController() {
        this.converterRouter = new ConverterRouter();
    }

    @PostConstruct
    public void init() {
        ConverterConfig.DOCUMENT_CONVERTER = documentConverter;
        ConverterConfig.OUT_DIR = workDir + File.separator + "out" + File.separator;
    }

    @PostMapping("to")
    public Result<ConvertResult> to(@RequestParam("file") MultipartFile file,
                                    String inputType,
                                    String outType) throws IOException {
        File tempFile = MultipartFileUtils.save(file, workDir);
        return Result.success(converterRouter.convert(ConvertInput
                .builder()
                .input(tempFile.getAbsolutePath())
                .inputType(inputType)
                .build(), outType));
    }

    @GetMapping("support")
    public Map<String, Set<String>> support()  {
        return converterRouter.supportMap();
    }

}
